<?php
namespace app\restaurant\model;

use app\BaseModel;
use app\member\model\Member;
use think\facade\Db;

class RefundOrder extends BaseModel
{
    //定义表名
    protected $name = 'longbing_card_restaurant_refund_order';



    protected $append = [

        'order_goods',

        'total_num'

    ];


    /**
     * @author chenniang
     * @DataTime: 2020-11-05 14:26
     * @功能说明:退款图片
     */
    public function getCancelImgAttr($value,$data){

        $value = !empty($value)?explode(',',$value):$value;

        return $value;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-05 11:57
     * @功能说明:总退款件数
     */
    public function getTotalNumAttr($value,$data){

        if(!empty($data['id'])){

            $order_goods_model = new RefundOrderGoods();

            $arr = $order_goods_model->where(['refund_id'=>$data['id']])->sum('goods_num');

            return $arr;

        }

    }


    /**
     * @author chenniang
     * @DataTime: 2020-10-10 14:46
     * @功能说明:子订单
     */
    public function getOrderGoodsAttr($value,$data){

        if(!empty($data['id'])){

            $order_goods_model = new RefundOrderGoods();

            $arr = $order_goods_model->orderList(['a.refund_id'=>$data['id']]);

            return $arr;

        }

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:04
     * @功能说明:添加
     */
    public function orderAdd($data){

        $data['create_time'] = time();

        $data['update_time'] = time();

        $res = $this->insert($data);

        return $res;

    }



    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:05
     * @功能说明:编辑
     */
    public function orderUpdate($dis,$data){

        $data['update_time'] = time();

        $res = $this->where($dis)->update($data);

        return $res;

    }


    /**
     * @param $dis
     * @param $page
     * @功能说明:
     * @author chenniang
     * @DataTime: 2020-11-05 11:41
     */
    public function orderList($dis,$page){

        $data = $this->where($dis)->order('id desc')->paginate($page)->toArray();

        return $data;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:06
     * @功能说明:列表
     */
    public function refundOrderList($dis,$mapor,$page=10){

        $data = $this->alias('a')
            ->join('longbing_card_restaurant_order b','a.order_id = b.id')
            ->join('longbing_card_restaurant_order_goods c','c.order_id = a.order_id')
            ->join('longbing_card_restaurant_refund_order_goods d','d.order_goods_id = c.id AND a.id = d.refund_id')
            ->where($dis)
            ->where(function ($query) use ($mapor){
                $query->whereOr($mapor);
            })
            ->field(['a.*','a.order_code as refund_order_code','b.order_code','b.order_type'])
            ->group('a.id')
            ->order('a.id desc')
            ->paginate($page)
            ->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:06
     * @功能说明:列表
     */
    public function adminRefundOrderList($dis,$page=10){

        $data = $this->alias('a')
            ->join('longbing_card_restaurant_order b','a.order_id = b.id')
            ->join('longbing_card_restaurant_order_goods c','c.order_id = a.order_id')
            ->join('longbing_card_restaurant_refund_order_goods d','d.order_goods_id = c.id AND d.refund_id = a.id')
            ->join('longbing_card_restaurant_store e','e.id = a.store_id')
            ->where($dis)
            ->field(['a.*','a.order_code as refund_order_code','b.order_code','b.order_type','e.title as store_title'])
            ->group('a.id')
            ->order('a.id desc')
            ->paginate($page)
            ->toArray();

        return $data;

    }

    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:43
     * @功能说明:详情
     */
    public function orderInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2020-10-13 09:59
     * @功能说明:今日订单笔数
     */
    public function storeOrderTodayCount($store_id,$uniacid){

        $dis = [

            'store_id' => $store_id,

            'uniacid'  => $uniacid,

            'status'   => 1
        ];

        $price = $this->where($dis)->whereDay('create_time')->count();

        return $price;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-10-13 09:59
     * @功能说明:今日订单笔数
     */
    public function storeOrderYesterdayCount($store_id,$uniacid){

        $dis = [

            'store_id' => $store_id,

            'uniacid'  => $uniacid,

            'status'   => 1
        ];

        $price = $this->where($dis)->whereTime('create_time','yesterday')->count();

        return $price;

    }

    /**
     * @author chenniang
     * @DataTime: 2020-10-13 10:41
     * @功能说明:
     *
     */
    public function storeOderCount($store_id,$day,$uniacid,$type=0){

        $dis = [

            'uniacid'  => $uniacid,

            'status'   => 2
        ];

        if(!empty($store_id)){

            $dis['store_id'] = $store_id;
        }

        if(!empty($day)){

            $dis['day']  = $day;
        }

        if($type==0){
            //订单笔数
            $price = $this->where($dis)->group('order_id')->count();

        }elseif($type==1){
            //付款人数
            $price = $this->where($dis)->group('order_id,user_id')->count();

        }elseif($type==2){
            //订单金额
            $price = $this->where($dis)->sum('refund_price');

            $price = round($price,2);

        }
        return $price;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-10-26 14:35
     * @功能说明:取消订单
     */
    public function cancelOrder($order){


        $insert = [

            'uniacid'     => $order['uniacid'],

            'order_id'    => $order['id'],

            'order_code'  => orderCode(),

            'status'      => 2,

            'user_id'     => $order['user_id'],

            'apply_price' => $order['pay_price'],

            'balance'     => $order['balance'],

            'refund_price'=> $order['pay_price'],

            'day'         => date('Y-m-d',time()),

            'store_id'    => $order['store_id'],

            'sh_time'     => time(),

            'goods_price' => $order['goods_price'],

            'total_lunch_price'   => $order['total_lunch_price'],

            'total_feeding_price' => $order['total_feeding_price'],

            'express_price' => $order['express_price'],

        ];

        $this->orderAdd($insert);

        $id = $this->getLastInsID();

        foreach ($order['order_goods'] as $v){

            $arr = [

                'uniacid'        => $v['uniacid'],

                'refund_id'      => $id,

                'order_goods_id' => $v['id'],

                'goods_num'      => $v['goods_num'],

                'goods_price'    => $v['pay_price'],

                'lunch_price'    => $v['lunch_price'],

                'feeding_price'  => $v['feeding_price'],

                'refund_price'   => round($v['pay_price']+$v['lunch_price'],2)
            ];

            Db::name('longbing_card_restaurant_refund_order_goods')->insert($arr);

        }

        return true;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-04 10:20
     * @功能说明:申请售后
     */
    public function applyRefundOrder($order,$list,$cancel_reason='',$cancel_img=''){
        //总商品价格
        $goods_fee   = 0;
        //总餐盒
        $lunch_fee   = 0;
        //总加料费
        $feeding_fee = 0;

        foreach ($list as &$value){

            if($order['id']!=$value['order_id']){

                return ['code'=>500,'msg'=>'订单信息错误'];
            }
            //商品退款价格
            $value['goods_fee'] = $value['pay_price']/$value['goods_num']*$value['apply_num'];

            $goods_fee += $value['goods_fee'];
            //餐盒费
            $value['lunch_fee'] = $value['lunch_price']/$value['goods_num']*$value['apply_num'];

            $lunch_fee += $value['lunch_fee'];
            //餐盒费
            $value['feeding_fee'] = $value['feeding_price']/$value['goods_num']*$value['apply_num'];

            $feeding_fee += $value['feeding_fee'];

        }

        $refund_price = round($goods_fee+$lunch_fee,2);

        $balance = !empty($order['balance'])?$refund_price:0;

        Db::startTrans();

        $insert = [

            'uniacid'     => $order['uniacid'],

            'order_id'    => $order['id'],

            'order_code'  => orderCode(),

            'status'      => 1,

            'user_id'     => $order['user_id'],
            //申请退款金额
            'apply_price' => $refund_price,

            'balance'     => $balance,
            //实际退款金额
            'refund_price'=> 0,

            'day'         => date('Y-m-d',time()),

            'store_id'    => $order['store_id'],

            'sh_time'     => 0,

            'goods_price' => $goods_fee,

            'total_lunch_price'   => $lunch_fee,

            'total_feeding_price' => $feeding_fee,
            //需要审核
            'type'                => 1,
            //退款原因
            'cancel_reason'       => $cancel_reason,
            //退款图片
            'cancel_img'          => !empty($cancel_img)?implode(',',$cancel_img):''

        ];

        $this->orderAdd($insert);

        $id = $this->getLastInsID();

        $order_goods_model = new OrderGoods();

        foreach ($list as $v){

            $arr = [

                'uniacid'        => $v['uniacid'],

                'refund_id'      => $id,

                'order_goods_id' => $v['id'],

                'goods_num'      => $v['apply_num'],

                'goods_price'    => $v['goods_fee'],

                'lunch_price'    => $v['lunch_fee'],

                'feeding_price'  => $v['feeding_fee'],

                'refund_price'   => round($v['goods_fee']+$v['lunch_fee'],2)
            ];

            Db::name('longbing_card_restaurant_refund_order_goods')->insert($arr);

            // dump($v['can_refund_num'],$v['apply_num']);exit;
            //减少子订单表面可以退款的数量
            $order_goods_model->where(['id'=>$v['id']])->update(['can_refund_num'=>$v['can_refund_num']-$v['apply_num']]);

        }

        Db::commit();

        return true;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-10-23 15:11
     * @功能说明:检测订单 过期则取消
     */
    public function checkOrder($uniacid,$payConfig,$store_id=0,$user_id = 0){

        $config_model = new Config();

        $config    = $config_model->configInfo(['uniacid'=>$uniacid]);

        $over_time = $config['refund_success_time']*60;
        //默认30分钟
        $over_time = !empty($over_time)?$over_time:30*60;

        $dis[]  = ['uniacid','=',$uniacid];

        $dis[]  = ['status','=',1];

        $dis[]  = ['user_cancel','=',0];

        $dis[]  = ['create_time','<',time()-$over_time];

        if(!empty($user_id)){

            $dis[] = ['user_id','=',$user_id];
        }

        if(!empty($store_id)){

            $dis[] = ['store_id','=',$store_id];
        }

        $order_id = $this->where($dis)->column('id');

        if(!empty($order_id)){

            foreach ($order_id as $value){

               $res =  $this->agreeRefund($value,0,$payConfig,1);

//               dump($res,$value);exit;

            }

        }
        return true;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-04 14:26
     * @功能说明:统一退款
     */
    public function agreeRefund($id,$price,$payConfig,$auto=0,$operation=0){

        $order_model = new Order();

        $order_goods_model = new OrderGoods();

        $refund_order = $this->orderInfo(['id'=>$id]);

        $price = $auto==1?$refund_order['apply_price']:$price;
        //付款订单
        $order = $order_model->orderInfo(['id'=>$refund_order['order_id']]);
        //支付金额
        $pay_price = $order['pay_price'];

        if($refund_order['status']!=1){

            return ['code'=>500,'msg'=>'订单状态错误'];
        }

        Db::startTrans();
        //修改退款订单状态
        $res = $this->orderUpdate(['id'=>$id],['refund_price'=>$price,'status'=>2,'sh_time'=>time(),'auto'=>$auto,'operation'=>$operation]);

        if($res!=1){

            Db::rollback();

            return ['code'=>500,'msg'=>'退款失败，请重试'];

        }
        $order_goods = $order_goods_model->refundOrderGoods($refund_order['order_goods']);
        //归还库存
        $order_goods_model->refundOrder($order_goods);
        //查看是否退完了
        $res = $this->refundGoodsNum($order['id']);

        if($res==1){
            //修改付款订单状态
            $order_model->orderUpdate(['id'=>$order['id']],['pay_type'=>-1]);

            $progress_model = new Progress();
            //添加进度
            $progress_model->cancelOrder($order['uniacid'],$order['order_code']);
        }

        if($refund_order['apply_price'] == $refund_order['balance']){

            $member_model = new Member();

            $member = $member_model->getMemberInfo(['user_id'=>$refund_order['user_id']]);
            //退回余额
            $res    = $member_model->memberUpdate(['user_id'=>$refund_order['user_id']],['stored'=>$member['stored']+$price]);

            if($res!=1){

                Db::rollback();

                return ['code'=>500,'msg'=>'退款失败,请重试'];
            }
            //余额退款
            $response = [

                'return_code' => 'SUCCESS',

                'result_code' => 'SUCCESS'
            ];

        }else{
            //微信退款
            $response = orderRefundApi($payConfig,$pay_price,$price,$order['transaction_id']);

        }

        //如果退款成功修改一下状态
        if ( isset( $response[ 'return_code' ] ) && isset( $response[ 'result_code' ] ) && $response[ 'return_code' ] == 'SUCCESS' && $response[ 'result_code' ] == 'SUCCESS' ) {

            $response['out_refund_no'] = !empty($response['out_refund_no'])?$response['out_refund_no']:$order['order_code'];

            $this->orderUpdate(['id'=>$id],['out_refund_no'=>$response['out_refund_no']]);

        }else {
            //失败就报错
            $discption = !empty($response['err_code_des'])?$response['err_code_des']:$response['return_msg'];

            Db::rollback();
//            if($auto==0){

                return ['code'=>500,'msg'=> $discption];
//            }

        }

        Db::commit();

        return true;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-13 11:05
     * @功能说明:该订单退款是否退完
     */
    public function refundGoodsNum($order_id){

        $order_goods_model = new OrderGoods();

        $dis[] = ['order_id','=',$order_id];

        $buy_num  = $order_goods_model->where($dis)->sum('goods_num');

        $where = [

            'a.order_id' => $order_id,

            'a.status'   => 2
        ];

        $refund_num = $this->alias('a')
            ->join('longbing_card_restaurant_refund_order_goods b','a.id = b.refund_id')
            ->where($where)
            ->group('a.id')
            ->sum('b.goods_num');


        $res = $buy_num>$refund_num?0:1;

        return $res;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-04 15:27
     * @功能说明:拒绝退款
     */
    public function noAgreeRefund($id,$operation=0){

        $refund_order = $this->orderInfo(['id'=>$id]);

        if($refund_order['status']!=1){

            return ['code'=>500,'msg'=>'订单状态错误'];
        }

        $res = $this->orderUpdate(['id'=>$refund_order['id']],['status'=>3,'sh_time'=>time(),'operation'=>$operation]);

        return $res;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-05 09:35
     * @功能说明:退款订单列表
     */
    public function refundOderList($dis,$page){


//        $data = $this->alias('a')
//                ->join('longbing_card_restaurant_order b','a.order_id = b.id')
//                ->


    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-17 09:56
     * @功能说明:
     */

    public function goodsNum($order_goods_id){

        $dis[] = ['a.status','=',2];

        $dis[] = ['b.order_goods_id','=',$order_goods_id];

        $num = $this->alias('a')
            ->join('longbing_card_restaurant_refund_order_goods b','a.id = b.refund_id')
            ->where($dis)
            ->group('b.id')
            ->sum('b.goods_num');

        return $num;

    }










}